package com.cos.listener;

import com.cos.fegin.api.GoodsService;
import com.cos.constant.MQ;
import com.cos.vo.Goods;
import com.rabbitmq.client.Channel;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.ResourceUtils;

import javax.annotation.PostConstruct;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

@Component
@Slf4j
public class ItemListener {
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private Configuration configuration;

    private String path;
    private Template template;
    private String paths;
    @PostConstruct
    public void initPath() throws Exception {
       ClassLoader classLoader = this.getClass().getClassLoader();
       URL templates = classLoader.getResource("templates");
        paths = templates.getPath();
        File file = ResourceUtils.getFile("shop-item/src/main/resources/templates");
        this.path = file.getAbsolutePath();
        //获取模板对象
       template = configuration.getTemplate("goodsitem.ftl");
    }
    @RabbitListener(queues = MQ.GOODS_ITEM_QUEUE)
    public void save(Goods goods, Channel channel, Message message) throws TemplateException, IOException {

        try { //设置模板数据
        Map<String, Object> data = new HashMap<>();
        data.put("gname", goods.getGname());
        data.put("gprice", goods.getGprice());
        data.put("gpngList", goods.getGpng().split("\\|"));
        //模板+数据 生成静态页面
        template.process(data, new FileWriter(path + File.separator + goods.getId() + ".html"));
        template.process(data, new FileWriter(paths + File.separator + goods.getId() + ".html"));
         channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (IOException e) {
           log.error("生成静态页面出现异常!!!",e);
           channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,false);
        }
    }
}
